
import { _decorator, Component, Layers, Node, resources, Sprite, SpriteFrame, UITransform } from 'cc';
import Levels from '../../Levels';
import { TileManager } from './TileManager';
import { createUINode, randomByRange } from '../../Utils';
import DataManager from '../../Runtime/DataManager';
import ResourceManager from '../../Runtime/ResourceManager';
const { ccclass, property } = _decorator;

@ccclass('TileMapManager')
export class TileMapManager extends Component {
    async init() {
        const { mapInfo } = DataManager.Instance
        const spriteFrames = await ResourceManager.Instance.loadDir("texture/tile/tile", SpriteFrame)
        // console.log("spriteFrames", spriteFrames)
        // console.log("mapInfo", mapInfo)
        DataManager.Instance.tileInfo = []
        for (let i = 0; i < mapInfo.length; i++) {
            const row = mapInfo[i]
            DataManager.Instance.tileInfo[i] = []
            for (let j = 0; j < row.length; j++) {
                const item = row[j]
                if (item.src === null || item.type === null) {
                    continue
                }

                // 地面有几种不同图片，可以随机获取，并且限制随机的量以保证大部分地面是干净的
                let number = item.src
                if ((number === 1 || number === 5 || number === 9) && i % 2 === 0 && j % 2 === 0) {
                    number += randomByRange(0, 4)
                }

                const node = createUINode()
                const imgSrc = `tile (${number})`
                const spriteFrame = spriteFrames.find(frame => frame.name === imgSrc) || spriteFrames[0]

                const tileManager = node.addComponent(TileManager)
                const type = item.type
                tileManager.init(type, spriteFrame, i, j)
                DataManager.Instance.tileInfo[i][j] = tileManager
                node.setParent(this.node)
            }
        }
    }
}
